package com.itheima.reggie.controller;

import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

//员工
@RestController
public class EmployeeController {

    @Autowired
    private HttpSession session;

    @Autowired
    private EmployeeService employeeService;

    //用户登录
    @PostMapping("/employee/login")//post请求
    public ResultInfo login(@RequestBody Map<String, String> map) {
        //1.获取到集合中的对象
        String username = map.get("username");
        String password = map.get("password");
        //2.调用方法查询,返回结果
        ResultInfo resultInfo = employeeService.login(username, password);

        //3.将信息保存到session中
        Employee employee = (Employee) resultInfo.getData();
        session.setAttribute("SESSION_EMPLOYEE", employee);
        //4.返回登录结果
        return resultInfo;
    }

    //用户退出
    @PostMapping("/employee/logout")
    public ResultInfo logout() {
        //1.注销当前用户的session
        session.invalidate();

        //2.返回成功标识
        return ResultInfo.success(null);
    }

    //员工查询
    @GetMapping("/employee/find")
    public ResultInfo findByName(String name) {

        //1.调用service查询
        List<Employee> employeeList = employeeService.findByName(name);
        //2.返回结果
        return ResultInfo.success(employeeList);
    }

    //新增员工
    @PostMapping("/employee")
    public ResultInfo save(@RequestBody Employee employee) {
        employeeService.save(employee);
        return ResultInfo.success(null);
    }

    //通过id查询
    @GetMapping("/employee/{id}")
    public ResultInfo findById(@PathVariable("id") String id) {
        Employee employee = employeeService.findById(id);
        return ResultInfo.success(employee);
    }

    //更新用户
    @PutMapping("/employee")
    public ResultInfo update(@RequestBody Employee employee) {
        employeeService.update(employee);
        return ResultInfo.success(null);
    }
}
